<template>
  <a-form :form="form">
    <a-row :gutter="24">
      <a-col :span="10">
        <a-form-item>
          <a-upload
            listType="picture-card"
            :fileList="fileList"
            class="avatar-uploader"
            @preview="handlePreview"
            @change="handleChange"
            :customRequest="customRequest"
            :remove="handleRemove"
            v-decorator="['picObj', {rules: []}]"
          >
            <div v-if="fileList.length < 1">
              <img style="width: 80%" :src="demoImg" alt="示例" />
              <div class="ant-upload-text">营业执照示例图片，点击上传</div>
            </div>
          </a-upload>
        </a-form-item>

        <preview-modal ref="previewModal" />
      </a-col>
      <a-col :span="14">
        <a-form-item v-show="false">
          <a-input
            :disabled="true"
            type="text"
            v-decorator="[
            'businessLicense',
            {rules: []}
          ]"
          />
        </a-form-item>
        <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="统一社会信用代码">
          <a-input
            type="text"
            placeholder="请输入"
            v-decorator="[
            'uscc',
            {rules: [{required: true, message: '请输入统一社会信用代码'}], validateTrigger: 'change'}
          ]"
          />
        </a-form-item>
        <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="法人代表">
          <a-input
            type="text"
            placeholder="请输入"
            v-decorator="[
            'legalRepresentative',
            {rules: [{required: true, message: '请输入法人代表'}], validateTrigger: 'change'}
          ]"
          />
        </a-form-item>
        <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="营业执照开始日期">
          <a-date-picker
            @change="(date, dateString) => dateChange(date, dateString, 'businessBegin')"
            placeholder="请选择"
            v-decorator="[
            'businessBegin',
            {rules: [{required: true, message: '请输入营业执照开始日期'}], validateTrigger: 'change'}
          ]"
          />
        </a-form-item>
        <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="营业执照结束日期">
          <a-input
            type="text"
            placeholder="请输入"
            v-decorator="[
            'businessEnd',
            {rules: [{required: true, message: '请输入营业执照结束'}], validateTrigger: 'change'}
          ]"
          />
          <!-- <a-date-picker
            :disabled="isLong"
            @change="(date, dateString) => dateChange(date, dateString, 'businessEnd')"
            placeholder="请选择"
            class="mr20"
            v-decorator="[
            'businessEnd',
            {rules: [{required: true, message: '请输入营业执照结束日期'}], validateTrigger: 'change'}
          ]"
          />-->
          <!-- <a-checkbox @change="checkChange" :checked="isLong">长期</a-checkbox> -->
        </a-form-item>
        <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="地址">
          <a-input
            type="text"
            placeholder="请输入"
            v-decorator="[
            'businessAddress',
            {rules: [{required: true, message: '请输入地址'}], validateTrigger: 'change'}
          ]"
          />
        </a-form-item>
        <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="经营范围">
          <a-textarea
            placeholder="请输入"
            :autosize="{ minRows: 3, maxRows: 6 }"
            v-decorator="[
            'businessScope',
            {rules: [{required: true, message: '请输入经营范围'}], validateTrigger: 'change'}
          ]"
          />
        </a-form-item>
      </a-col>
    </a-row>
  </a-form>
</template>

<script>
import { businessLicenseUpload, deleteUploadPic } from '@/api/supplier'
import PreviewModal from '@/components/PreviewModal'
import { openNotification, getBase64 } from '@/utils/util'
import pick from 'lodash.pick'
import moment from 'moment'
import demoImg from '@/assets/license.jpeg'

export default {
  components: {
    PreviewModal
  },
  data() {
    return {
      demoImg,
      loading: false,
      imageUrl: '',
      form: this.$form.createForm(this),
      fileList: [],
      labelCol: {
        xs: { span: 24 },
        sm: { span: 5 },
        md: { span: 7 }
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 16 },
        md: { span: 16 }
      },
      mdl: {},
      businessBegin: null,
      businessEnd: null,
      isLong: false
    }
  },
  methods: {
    dateChange(date, dateString, key) {
      this[key] = dateString
    },
    // checkChange(e) {
    //   console.log('e', e)
    //   const {
    //     target: { checked }
    //   } = e
    //   this.isLong = e.target.checked
    //   if (checked) {
    //     this.$nextTick(() => {
    //       this.form.setFieldsValue({
    //         businessEnd: '长期'
    //       })
    //     })
    //   } else {
    //     this.$nextTick(() => {
    //       this.form.setFieldsValue({
    //         businessEnd: ''
    //       })
    //     })
    //   }
    // },
    edit(type, record) {
      console.log('license record', record)
      this.mdl = Object.assign({}, record)
      if (record.businessBegin) {
        this.businessBegin = record.businessBegin
      }
      // if (record.businessEnd) {
      //   // 结束时间为长期时，checked赋值为true
      //   if (record.businessEnd === '长期') {
      //     this.isLong = true
      //   } else {
      //     // 结束时间为字符串格式时，赋值，moment转化
      //     this.businessEnd = record.businessEnd
      //     this.$nextTick(() => {
      //       this.form.setFieldsValue({
      //         businessEnd: moment(record.businessEnd)
      //       })
      //     })
      //   }
      // }
      if (record.savePath) {
        this.fileList = [{ uid: '0', name: '营业执照', url: record.savePath }]
      }
      this.$nextTick(() => {
        this.form.setFieldsValue({
          businessBegin: moment(record.businessBegin)
        })
        this.form.setFieldsValue(pick(this.mdl, 'businessLicense', 'uscc', 'legalRepresentative', 'businessAddress', 'businessEnd', 'businessScope'))
      })
    },
    // 父组件拿营业执照的对象信息
    getFormData() {
      const {
        form: { validateFields },
        businessBegin
        // businessEnd
      } = this
      validateFields(['businessLicense', 'uscc', 'legalRepresentative', 'businessBegin', 'businessEnd', 'businessAddress', 'businessScope'], { force: true }, async (err, values) => {
        if (!err) {
          console.log('license values', { ...values, businessBegin }) // businessEnd
          this.$emit('sendData', { ...values, businessBegin }, 2)
        } else {
          this.$emit('notSubmit', false, 1)
        }
      })
    },
    // 父组件调用重置
    reset() {
      this.form.resetFields()
    },
    // 预览图片，显示大图
    handlePreview(file) {
      console.log('file', file)
      // let url = file.savePath ? file.savePath : file.url
      this.$refs.previewModal.show([file.url])
    },
    handleChange(info) {
      this.fileList = info.fileList

      console.log('info', info)
      if (info.file.status === 'uploading') {
        this.loading = true
        return
      }
      if (info.file.status === 'done') {
        // Get this url from response in real world.
        getBase64(info.file.originFileObj, imageUrl => {
          this.imageUrl = imageUrl
          this.loading = false
        })
      }
    },
    // 删除方法
    handleRemove(info, type) {
      console.log('remove info', info)
      this.$nextTick(() => {
        this.form.resetFields()
      })
    },
    // 覆盖原本的上传方法
    customRequest(info) {
      const formData = new FormData()
      formData.append('file', info.file)
      // 调方法，post，body 放入 formData
      businessLicenseUpload(formData).then(res => {
        if (res.data !== null) {
          openNotification('success', '营业执照识别成功，部分未识别内容请手动填写')
          const { data } = res
          // console.log('data', data)
          this.fileList = [{ ...this.fileList[0], status: 'done', url: data[0].savePath }]
          // console.log('fileList', this.fileList)
          let date = data[1].validityDate
          if (date === '长期') {
            this.isLong = true
          }
          const newDate = date
            .replace('年', '-')
            .replace('月', '-')
            .replace('日', '')
          this.$nextTick(() => {
            this.form.setFieldsValue({
              businessLicense: data[0].uploadId,
              uscc: data[1].socialCreditCode,
              legalRepresentative: data[1].legalPerson,
              businessEnd: newDate,
              businessAddress: data[1].address
            })
          })
        }
      })
    }
  }
}
</script>

<style scoped>
.avatar-uploader >>> .ant-upload {
  width: 100%;
  height: 300px;
}
.avatar-uploader >>> .ant-upload-list {
  width: 100%;
}

.avatar-uploader >>> .ant-upload-list-item {
  width: 100%;
  height: 400px;
}
.ant-upload-select-picture-card i {
  font-size: 32px;
  color: #999;
}

.ant-upload-select-picture-card .ant-upload-text {
  margin-top: 8px;
  color: #666;
}
</style>